package com.haixue.android.academy.view;

import android.academy.haixue.com.haixue.R;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Created by ren on 2015/6/3 0003.
 */
public class LoadingView extends RelativeLayout {
    private RotateAnimation rotateAnimation;
    private TextView tv;
    private ImageView iv;
    private int defResId =R.drawable.progress_loading_image;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        View inflate = View.inflate(getContext(), R.layout.layout_loading, null);
        initView(inflate);
        addView(inflate, lp);

        Drawable drawable = getResources().getDrawable(defResId);

        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());

        rotateAnimation = new RotateAnimation(0, 359,
                drawable.getIntrinsicWidth() / 2,
                drawable.getIntrinsicHeight() / 2);
        rotateAnimation.setDuration(800);
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        iv.setBackgroundResource(defResId);
        iv.startAnimation(rotateAnimation);
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (visibility==VISIBLE){
            iv.startAnimation(rotateAnimation);
        }else{
            iv.clearAnimation();
        }

    }

    private void initView(View view) {
        tv = (TextView) view.findViewById(R.id.tv);
        iv = (ImageView) view.findViewById(R.id.iv);
    }

    public LoadingView(Context context) {
        super(context);
        init();
    }

    public LoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
}
